import { SiteDTO, ServiceProxy } from './../../../../shared/service-proxy/service-proxies';
import { Component, OnInit, Output, EventEmitter, Injector } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-set-site-remark-modal',
  templateUrl: './set-site-remark-modal.component.html',
  styleUrls: ['./set-site-remark-modal.component.less']
})
export class SetSiteRemarkModalComponent extends AppComponentBase implements OnInit {
  @Output() modalSave = new EventEmitter<any>();
  isVisible = false;
  isOkLoading = false;
  site: SiteDTO;
  title: string;
  validateForm: FormGroup;
  constructor(injector: Injector, private _service: ServiceProxy, private fb: FormBuilder) {
    super(injector)
  }

  ngOnInit() {
    this.site = new SiteDTO();
    this.validateForm = this.fb.group({
      reason: [null, [Validators.required, Validators.maxLength(255)]]
    });
  }

  handleCancel() {
    this.isVisible = false;
  }

  handleOk() {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.valid) {
      this._service.updateSiteStatusUsingPUT(this.site.id, this.site).subscribe(result => {
        this.isOkLoading = false;
        if (result.success) {
          this.message.success(this.l("save_success"));
          this.modalSave.emit();
          this.isVisible = false;
        }
        else {
          this.message.info(this.l(result.error.message));
        }
      }, error => {
        this.isOkLoading = false;
        this.message.error(this.l(error.message));
      });
    } else {
      this.isOkLoading = false;
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }
  }

  show(id: string, enableFlag: boolean) {
    this.isVisible = true;
    this.site.id = id;
    this.site.enableFlag = !enableFlag;
    if (this.site.enableFlag)
      this.title = this.l("enable");
    else
      this.title = this.l("disenable");
    this.site.reason = "";
  }
}
